Cesium.Ion.defaultAccessToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiI5ZDE1MmJlNS1kOTEzLTQ3ZDUtOTcxYi05NDUwNzVlMTRiYWQiLCJpZCI6Mjc3NTUyLCJpYXQiOjE3NDAwMjE0MDh9.0xbWcO8SUU073hs_s85E_0XNCugQ4E-mvEPRdmwGnw0';
// 初始化Mars3D地图/
var map;
var graphicLayer; // 添加全局图层变量
var formatDistance = mars3d.MeasureUtil.formatDistance
var formatTime = mars3d.Util.formatTime
var mapOptions = {
  scene: {
    center: { lng: 106.584, lat: 20.848, alt: 1000, heading: 0, pitch: -30 },
    showSun: true,
    showMoon: true,
    showSkyBox: true,
    showSkyAtmosphere: true,
    fog: true,
    fxaa: true,
    globe: {
      showGroundAtmosphere: false, // 关闭大气（球表面白蒙蒙的效果）
      depthTestAgainstTerrain: true,
      baseColor: "#546a53"
    },
    cameraController: {
      zoomFactor: 14.0,
      minimumZoomDistance: 1,
      maximumZoomDistance: 50000000,
      enableRotate: true,
      enableZoom: true
    },
    mapProjection: mars3d.CRS.EPSG3857, // 2D下展示墨卡托投影
    mapMode2D: Cesium.MapMode2D.INFINITE_SCROLL // 2D下左右一直可以滚动重复世界地图
  },
  terrain:{
    url: "http://data.mars3d.cn/terrain",
    show: true
  },
  basemaps: [
    {
      name: "天地图影像",
      icon: "https://data.mars3d.cn/img/thumbnail/basemap/tdt_img.png",
      type: "tdt",
      layer: "img_d",
      show: true
    }
  ],
  control: {
    clockAnimate: true, // 时钟动画控制(左下角)
    timeline: true, // 是否显示时间线控件
    compass: { style: { top: "10px", left: "5px" } }
  }
}

// 初始化地图
function initMap() {
  try {
    console.log("正在初始化地图...");
    // 检查dom元素是否存在
    var mapContainer = document.getElementById("map");
    if (!mapContainer) {
      console.error("地图容器元素不存在!");
      return null;
    }
    // 确认必要的库已加载
    if (typeof mars3d === 'undefined') {
      console.error("mars3d库未加载!");
      return null;
    }
    if (typeof Cesium === 'undefined') {
      console.error("Cesium库未加载!");
      return null;
    }
    // 创建三维地球场景
    map = new mars3d.Map("map", mapOptions);
    
    // 创建矢量数据图层
    graphicLayer = new mars3d.layer.GraphicLayer();
    map.addLayer(graphicLayer);
    
    // 监听地形加载事件
    map.on(mars3d.EventType.terrainLoadSuccess, function(event) {
      console.log("地形服务加载成功", event);
    });
    map.on(mars3d.EventType.terrainLoadError, function(event) {
      console.log("地形服务加载失败", event);
    });
    
    // 监听地图加载完成事件，在加载完成后添加路线漫游
    map.on(mars3d.EventType.load, function (event) {
      console.log("地图加载完成，准备添加路线漫游");
      addFixedRouteToGround();
    });
    
    return map;
  } catch (error) {
    console.error("地图初始化失败:", error);
    // 显示错误信息到页面上
    var mapContainer = document.getElementById("map");
    if (mapContainer) {
      mapContainer.innerHTML = '<div style="color:red;padding:20px;">地图加载失败: ' + error.message + '</div>';
    }
    return null;
  }
}
// 添加贴地路线漫游功能
function addFixedRouteToGround() {
  console.log("开始添加路线漫游...");
  fetch('http://localhost:4000/2Dtrack/get_track/Himantopus himantopus') // 你的后端接口地址
    .then(res => res.json())
    .then(json => {
      if (json.code !== 200) {
        console.error("轨迹数据获取失败", json.msg);
        return;
      }
      console.log("轨迹数据获取成功", json);
      const features = json.data.features;
      
      // 1. 获取路线点
      const lineFeature = features.find(f => f.geometry.type === "LineString");
      let pointList = [];
      if (lineFeature) {
        pointList = lineFeature.geometry.coordinates.map(coord => [coord[0], coord[1]]); // 默认高度50
      }
      // 2. 获取节点事件（如需后续处理）
      const pointFeatures = features.filter(f => f.geometry.type === "Point");

      // 3. 创建固定路线漫游对象
      const fixedRoute = new mars3d.graphic.FixedRoute({
        name: "贴地表表面漫游",
        position: {
          type: "time",
          speed: 5000,
          list: pointList
        },
        clockLoop: true,
        camera: {
          type: "gs",
          pitch: -30,
          radius: 200
        },
        model: {
          url: "scene.gltf", // 替换为你的模型路径
          heading: 180,
          mergeOrientation: true,
          minimumPixelSize: 100
        },
        polyline: {
          color: "rgba(0,255,0,1.0)",
          width: 2
        },
        path: {
          color: "rgba(255,255,0,0.5)",
          width: 2,
          trailTime: 0
        }
      });

      // 添加到图层
      graphicLayer.addGraphic(fixedRoute);


      // 添加事件监听
      fixedRoute.on(mars3d.EventType.start, function () {
        console.log("漫游开始");
      });

      fixedRoute.on(mars3d.EventType.end, function () {
        console.log("漫游结束");
      });

      let lastEventId = null;
      fixedRoute.on(mars3d.EventType.change, function (event) {
   let lng, lat;
  if (Array.isArray(event.point)) {
    lng = event.point[0];
    lat = event.point[1];
  } else if (event.point && typeof event.point === 'object') {
    lng = event.point.lng ?? event.point.lon ?? event.point.longitude;
    lat = event.point.lat ?? event.point.latitude;
  }
  if (typeof lng !== 'number' || typeof lat !== 'number') {
    console.warn('event.point 结构异常', event.point);
    return;
  }
const videoUrls = [
  "http://localhost:4000/3Dtrack/get_video/Himantopus himantopus1",
  "http://localhost:4000/3Dtrack/get_video/Himantopus himantopus2"
];
  for (let i = 0; i < pointFeatures.length; i++) {
    const pt = pointFeatures[i].geometry.coordinates;
    const props = pointFeatures[i].properties || {};
    const dist = Math.sqrt(
      Math.pow(pt[0] - lng, 2) +
      Math.pow(pt[1] - lat, 2)
    );
    if (dist < 1e-4 && props.event_id && props.event_id !== lastEventId) {
      lastEventId = props.event_id;
      // 只在有 event_id 的原始点且到达该点时触发
      console.log("到达关键节点", props.event_id, props.time, props.stage, props.activity);
      document.getElementById("infoTime").innerText = props.time || "-";
      document.getElementById("infoStage").innerText = props.stage || "-";
      document.getElementById("infoActivity").innerText = props.activity || "-";
      // 动态切换视频
      const video = document.getElementById('videoContainer');
      if (video && videoUrls[i]) {
        video.src = videoUrls[i];
        video.load();
        video.play();
      }
      break;
    }
    document.getElementById("infoLng").innerText = lng;
    document.getElementById("infoLat").innerText = lat;
    document.getElementById("infoAlt").innerText = event.point.alt|| 0;
  }
});

      // 6. 添加键盘控制
      map.on(mars3d.EventType.keydown, function (event) {
        if (event.keyCode === 32) { // 空格键控制暂停/继续
          if (fixedRoute.isPause) {
            fixedRoute.proceed();
            console.log("漫游继续");
          } else {
            fixedRoute.pause();
            console.log("漫游暂停");
          }
        }
      });

      // 7. 计算贴地点
      console.log("正在计算贴地点...");
      if (typeof showLoading === 'function') showLoading();

      fixedRoute.autoSurfaceHeight({ exact: true, offset: 800 }).then(() => {
        if (typeof hideLoading === 'function') hideLoading();
        console.log("贴地点计算完成，开始漫游");
        startFly(fixedRoute);
      }).catch(error => {
        console.error("贴地点计算失败:", error);
        if (typeof hideLoading === 'function') hideLoading();
      });
    })
    .catch(err => {
      console.error("添加路线漫游过程中发生异常:", err);
    });
}


// 开始漫游
function startFly(fixedRoute) {
  try {
    fixedRoute.start();
  } catch (e) {
    console.error("开始漫游过程中发生异常:", e);
  }
}


// 添加loading函数
function showLoading() {
  console.log("正在加载...");
  // 这里可以添加显示加载动画的代码
}

function hideLoading() {
  console.log("加载完成");
  // 这里可以添加隐藏加载动画的代码
}

// 页面加载完成后执行
window.addEventListener("load", function () {
  var mapInstance = initMap();
});